package vip.xiaonuo.modular.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.factory.TreeBuildFactory;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.modular.business.entity.BiUserIndexType.BiUserIndexType;
import vip.xiaonuo.modular.business.entity.BiUserIndexType.DefaultIndexVo;
import vip.xiaonuo.modular.business.mapper.BiIndexTypeMapper;
import vip.xiaonuo.modular.business.mapper.BiUserIndexTypeMapper;
import vip.xiaonuo.modular.business.param.BiUserIndexType.EditParam;
import vip.xiaonuo.modular.business.param.BiUserIndexType.QueryParam;
import vip.xiaonuo.modular.business.param.BiUserIndexType.StyleParam;
import vip.xiaonuo.modular.business.service.BiUserIndexTypeService;
import vip.xiaonuo.modular.business.service.IndexTypeManageService;
import vip.xiaonuo.modular.business.service.UserIndexColorService;
import vip.xiaonuo.modular.business.util.UserIndexTypeHandler;
import vip.xiaonuo.modular.entitys.UserIndexTree;
import vip.xiaonuo.modular.manage.biIndexItem.enums.BiIndexItemEnum;
import vip.xiaonuo.modular.manage.biUserIndexSpu.entity.BiUserIndexSpu;
import vip.xiaonuo.modular.manage.biUserIndexSpu.service.impl.BiUserIndexSpuServiceImpl;
import vip.xiaonuo.modular.manage.biindexfunction.entity.BiIndexFunction;
import vip.xiaonuo.modular.manage.biindexfunction.service.BiIndexFunctionService;
import vip.xiaonuo.modular.manage.biindextype.entity.BiIndexType;
import vip.xiaonuo.modular.manage.biindextype.service.BiIndexTypeService;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author cy
 * @Date 2022/8/3 14:47
 * @Version 1.0
 */
@Service
public class IndexTypeManageServiceImpl implements IndexTypeManageService {
    @Resource
    private BiIndexTypeService biIndexTypeService;
    @Resource
    private BiUserIndexTypeService biUserIndexTypeService;
    @Resource
    private BiUserIndexSpuServiceImpl biUserIndexSpuService;
    @Resource
    private BiUserIndexTypeMapper biUserIndexTypeMapper;

    @Resource
    private BiIndexTypeMapper biIndexTypeMapper;

    @Resource
    private UserIndexColorService userIndexColorService;


    @Resource
    private BiIndexFunctionService biIndexFunctionService;

    @Override
    public UserIndexTree indexTypeTree(QueryParam param) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        //获取指标类型树
        LambdaQueryWrapper<BiIndexType> wrapper = new LambdaQueryWrapper<>();
        if(param != null){
            if (StringUtils.isNotEmpty(param.getType())) {
                wrapper.eq(BiIndexType::getType, param.getType());
            }
            if (CollectionUtil.isNotEmpty(param.getIndexTypeIds())) {
                wrapper.in(BiIndexType::getId, param.getIndexTypeIds());
            }
        }
        List<BiIndexType> indexTypes  = biIndexTypeService.list(wrapper);
        addIndexTreeNode(indexTypes);
        UserIndexTypeHandler handler = new UserIndexTypeHandler();
//        for (BiIndexType el : indexTypes) {
//            if("Y".equals(el.getIsDefault())){
//                el.setIco(userIndexColorService.getIndexColorIco(el.getId()));
//            }
//        }

        UserIndexTree tree = handler.rootTree(indexTypes);
        //获取指定用户已选指标
        List<BiUserIndexType> biUserIndexTypes = biUserIndexTypeService.list(sysLoginUser.getId());
        handler.setSelect(tree,biUserIndexTypes);
        return tree;
    }

    private void addIndexTreeNode(List<BiIndexType> indexTypes) {
        Set<Long> pids = new HashSet<>();
        List<Long> searchIds = indexTypes.stream().map(BiIndexType::getId).collect(Collectors.toList());
        indexTypes.forEach(el ->{
            String pidStr = el.getPids();
            for(String pida : StringUtils.split(pidStr, "],")) {
                if (!StringUtils.equals(pida, "[0")) {
                    Long id =Long.valueOf(pida.substring(1));
                    if (!searchIds.contains(id))
                        pids.add(id);
                }
            }
        });
        if (CollectionUtil.isNotEmpty(pids)) {
            QueryWrapper<BiIndexType> wrapper = new QueryWrapper<>();
            wrapper.lambda().in(BiIndexType::getId, pids);
            List<BiIndexType> biIndexTypes = biIndexTypeService.getBaseMapper().selectList(wrapper);
            biIndexTypes.forEach(el -> {
                BiIndexType vo = new BiIndexType();
                BeanUtil.copyProperties(el,vo);
                indexTypes.add(vo);
            });
        }
    }

    @Transactional
    @Override
    public void edit(EditParam param) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        //删除历史用户指标配置
        biUserIndexTypeService.removeByUserId(sysLoginUser.getId());
        //插入最新指标配置
        List<Long> nodes = JSONObject.parseArray(param.getSelects(),String.class).stream().map(o->Long.parseLong(o)).collect(Collectors.toList());
        List<BiIndexType> indexTypes = biIndexTypeService.findByIds(nodes);

        List<BiUserIndexType> biUserIndexTypes = indexTypes.stream().map(o->{
            BiUserIndexType indexType = new BiUserIndexType();
            indexType.setUserId(sysLoginUser.getId());
            indexType.setIndexTypeId(o.getId());
            indexType.setIsShow(CommonConstant.STATUS_Y.equals(o.getIsDefault())?CommonConstant.STATUS_Y:null);
            indexType.setCreateTime(new Date());
            return indexType;
        }).collect(Collectors.toList());
        biUserIndexTypeService.saveBatch(biUserIndexTypes);
    }

    @Override
    public List<DefaultIndexVo> defaultList() {
        // 获取默认指标
        LambdaQueryWrapper<BiIndexType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BiIndexType::getIsDefault, "Y");
        List<BiIndexType> types = biIndexTypeMapper.selectList(wrapper);
        List<DefaultIndexVo> list = new ArrayList<>();
        for (BiIndexType t : types) {
            DefaultIndexVo vo = new DefaultIndexVo();
            BeanUtil.copyProperties(t, vo);
//            String indexColorIco = userIndexColorService.getIndexColorIco(vo.getId());
//            vo.setIco(indexColorIco);
            // 增加指标说明，公式说明，图片信息
            JSONObject jsonData = new JSONObject();
            jsonData.put("description", t.getDescription());
            BiIndexFunction biIndexFunction = biIndexFunctionService.lambdaQuery()
                    .eq(BiIndexFunction::getIndexTypeId,vo.getId())
                    .last(" limit 1 ").one();
            if (biIndexFunction != null) {
                jsonData.put("functionMsg",biIndexFunction.getFunctionMsg());
                jsonData.put("imageUrl",biIndexFunction.getImageUrl());
            }else{
                jsonData.put("functionMsg","");
                jsonData.put("imageUrl","");
            }
            // 查询用户指标的颜色
//            BiUserIndexColor colorParm = new BiUserIndexColor();
//            colorParm.setIndexTypeId(vo.getId());
//            BiUserIndexColor biIndexColor = userIndexColorService.getBiIndexColor(colorParm);
//            if (biIndexColor != null) {
//                jsonData.put("color",biIndexColor.getColor());
//            }
            vo.setJsonData(jsonData);
            list.add(vo);
        }
        return list;
//        return biUserIndexTypeMapper.defaultList(sysLoginUser.getId());
    }

    public int customAdd(DefaultIndexVo vo) {
        //获取登录用户信息
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        LambdaQueryWrapper<BiUserIndexType> wrapper = new LambdaQueryWrapper();
        wrapper.eq(BiUserIndexType::getIndexTypeId,vo.getId());
        wrapper.eq(BiUserIndexType::getUserId,sysLoginUser.getId());
        int i = biUserIndexTypeService.count(wrapper);
        if(i == 0){
            BiUserIndexType userIndexType = new BiUserIndexType();
            userIndexType.setUserId(sysLoginUser.getId());
            userIndexType.setIndexTypeId(vo.getId());
            userIndexType.setIsShow(vo.getIsShow());
            userIndexType.setCreateTime(new Date());
            biUserIndexTypeService.save(userIndexType);
            return 1;
        }
        return 0;
    }
    public void customDelete(DefaultIndexVo vo) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        LambdaUpdateWrapper<BiUserIndexType> wrapper = new LambdaUpdateWrapper();
        wrapper.eq(BiUserIndexType::getUserId,sysLoginUser.getId());
        wrapper.eq(BiUserIndexType::getIndexTypeId, vo.getId());
        List<BiUserIndexType> biUserIndexTypes = biUserIndexTypeMapper.selectList(wrapper);
        for (BiUserIndexType b : biUserIndexTypes) {
            biUserIndexTypeMapper.deleteById(b.getId());
        }
    }
    public  List<DefaultIndexVo> customList() {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        // 這裏的 customList 查詢的是biUserIndexType，用戶自定義指標
        return biUserIndexTypeMapper.customList(sysLoginUser.getId(),null);
    }

    /**
     * 返回数状结构
     * @return
     */
    @Override
    public List<DefaultIndexVo> customTree(DefaultIndexVo param) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        List<DefaultIndexVo> defaultIndexVos = biUserIndexTypeMapper.customList(sysLoginUser.getId(),param.getType());
        Set<Long> pids = new HashSet<>();
        List<Long> searchIds = defaultIndexVos.stream().map(DefaultIndexVo::getId).collect(Collectors.toList());
        defaultIndexVos.forEach(el ->{
            String pidStr = el.getPids();
            for(String pida : StringUtils.split(pidStr, "],")) {
                if (!StringUtils.equals(pida, "[0")) {
                    Long id =Long.valueOf(pida.substring(1));
                    if (!searchIds.contains(id))
                        pids.add(id);
                }
            }
        });
        if (CollectionUtil.isNotEmpty(pids)) {
            QueryWrapper<BiIndexType> wrapper = new QueryWrapper<>();
            wrapper.lambda().in(BiIndexType::getId, pids);
            List<BiIndexType> biIndexTypes = biIndexTypeMapper.selectList(wrapper);
            biIndexTypes.forEach(el -> {
                DefaultIndexVo vo = new DefaultIndexVo();
                BeanUtil.copyProperties(el,vo);
                defaultIndexVos.add(vo);
            });
        }
        defaultIndexVos.forEach(el ->{
//            el.setIco(userIndexColorService.getIndexColorIco(el.getId()));
            // 增加指标说明，公式说明，图片信息
            JSONObject jsonData = new JSONObject();
            jsonData.put("description", el.getDescription());
            BiIndexFunction biIndexFunction = biIndexFunctionService.lambdaQuery()
                    .eq(BiIndexFunction::getIndexTypeId,el.getId())
                    .last(" limit 1 ").one();
            if (biIndexFunction != null) {
                jsonData.put("functionMsg",biIndexFunction.getFunctionMsg());
                jsonData.put("imageUrl",biIndexFunction.getImageUrl());
            }else{
                jsonData.put("functionMsg","");
                jsonData.put("imageUrl","");
            }
            // 查询用户指标的颜色
//            BiUserIndexColor colorParm = new BiUserIndexColor();
//            colorParm.setIndexTypeId(el.getId());
//            BiUserIndexColor biIndexColor = userIndexColorService.getBiIndexColor(colorParm);
//            if (biIndexColor != null) {
//                jsonData.put("color",biIndexColor.getColor());
//            }
            el.setJsonData(jsonData);
        });
        return new TreeBuildFactory<DefaultIndexVo>().doTreeBuild(defaultIndexVos);
    }

    @Override
    public void editList(List<DefaultIndexVo> editList) {
        //获取登录用户信息
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        //删除历史用户指标配置
        biUserIndexTypeService.removeByUserId(sysLoginUser.getId());
        List<BiUserIndexType> biUserIndexTypes =  editList.stream().map(o->{
            BiUserIndexType userIndexType = new BiUserIndexType();
            userIndexType.setUserId(sysLoginUser.getId());
            userIndexType.setIndexTypeId(o.getId());
            userIndexType.setIsShow(o.getIsShow());
            userIndexType.setCreateTime(new Date());
            return userIndexType;
        }).collect(Collectors.toList());
        biUserIndexTypeService.saveBatch(biUserIndexTypes);
    }

    @Override
    public void userStyle(StyleParam param) {
        //获取用户id
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        BiUserIndexSpu spu = new BiUserIndexSpu();
        //TODO 待修改  每次只修改一个指标样式
        spu.setUserId(sysLoginUser.getId());
        spu.setIndexTypeId(param.getTypeId());
        StringBuffer stb = new StringBuffer();

        stb.append(BiIndexItemEnum.CRUDENESS.getCode()+":"+param.getCrudeness()+",");
        stb.append(BiIndexItemEnum.COLOR.getCode()+":"+param.getColor()+",");
        stb.append(BiIndexItemEnum.FILL_COLOR.getCode()+":"+param.getFillColor());
        spu.setStyle(stb.toString());
        spu.setUpdateTime(new Date());
        spu.setUpdateUser(sysLoginUser.getId());
        BiUserIndexSpu oldSpu = biUserIndexSpuService.findByUserIdAndIndexId(sysLoginUser.getId(),param.getTypeId());
        if(oldSpu!=null){
            spu.setId(oldSpu.getId());
            biUserIndexSpuService.updateById(spu);
        }else{
            biUserIndexSpuService.save(spu);
        }
    }



}
